package com.sentiment.db;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.sentiment.obj.Similarity;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class SimilarityDB {
	private MongoClient mongoClient;
	private MongoDatabase mongodb;
	private MongoCollection<Document> mongoCollection;

	public SimilarityDB() {

		mongoClient = new MongoClient();

		mongodb = mongoClient.getDatabase("detection");

		mongoCollection = mongodb.getCollection("simCollection");
	}

	public void DBClose() {
		mongoClient.close();
	}

	/**
	 * 更新SimilarityDB中的一个Smilarity对象 记录着相似度的细节
	 * @param data 传入的Smilarity
	 */
	public void updateData(Similarity data){
		Document targetDoc = new Document("srcId",data.getSrcId());
		Document updateDoc = new Document("$set",new Document("similarDegree",data.getSimilarDegree()).append("detail", data.getDetail()))
				.append("$currentDate", new Document("lastModified",true));
		
		mongoCollection.updateOne(targetDoc, updateDoc);
	}
	/**
	 * @param data
	 *            待存入数据库的数据结构
	 */
	public void insertData(Similarity data) {

		// 创建一个document并插入
		Document doc = new Document("srcId",data.getSrcId()).append("detail", data.getDetail())
				.append("similarDegree", data.getSimilarDegree());

		mongoCollection.insertOne(doc);
	}

	public Similarity findDataByKeyAndVal(String key, String val) {
		Document mydoc = mongoCollection.find(Filters.eq(key, val)).first();
		if (mydoc == null)
			return null;
		Similarity s = new Similarity(mydoc);
		return s;
	}
	
	public List<Similarity> findAllDataByKeyAndVal(String key,String val){
		final List<Similarity> li = new ArrayList<Similarity>();
		FindIterable<Document> iter = mongoCollection.find(Filters.eq(key, val));
		iter.forEach(new Block<Document>( ){

			@Override
			public void apply(final Document doc) {
				// TODO Auto-generated method stub
				Similarity cp = new Similarity(doc);
				li.add(cp);
			}
			
		});
		return li;
	}

	public void cleanAll() {
		// 清理掉collection中原有的数据
		mongoCollection.drop();
	}
}
